package com.pzh.assignment.common.shiro.bean;

import com.pzh.assignment.entity.Role;
import com.pzh.assignment.entity.User;
import com.pzh.assignment.service.IRoleService;
import com.pzh.assignment.service.IUserService;
import com.pzh.assignment.common.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("authorizer")
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 能进入这里说明用户已经通过验证了
        AccountProfile profile = (AccountProfile) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(profile.getRole().getName());
        return simpleAuthorizationInfo;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken)authenticationToken;
        String userId = jwtUtils.getTokenInfo((String) jwtToken.getPrincipal()).getClaim("id").asString();
        User user = userService.getById(Integer.parseInt(userId));
        if (user == null){
            throw new UnknownAccountException("账户不存在");
        }
        Role role = roleService.getById(user.getRoleId());

        AccountProfile profile = new AccountProfile(user.getId(), user.getUsername(), role, user.getGroupId());

        return new SimpleAuthenticationInfo(profile, jwtToken.getCredentials(), getName());
    }
}
